<template>
  <div class="task-detail-container">

    <!-- 任务基本信息 -->
    <el-card class="task-info-card">
          <template #header>
      <div class="card-header-with-back">
        <el-button 
          type="info" 
          plain 
          size="small"
          @click="handleGoBack"
        >
          <el-icon><ArrowLeft /></el-icon> 返回
        </el-button>
        <span>任务详情</span>
      </div>
    </template>
      <div class="task-header">
        <el-tag :type="getStatusType(taskdetail.status)" size="large">{{ taskdetail.status }}</el-tag>
        <span class="task-type">{{ taskdetail.type }}</span>
      </div>
      
      <h1 class="task-title">{{ taskdetail.title }}</h1>
      
      <div class="task-meta">
        <div class="meta-item">
          <el-icon><User /></el-icon>
          <span>发布人: {{ taskdetail.createdBy }}</span>
        </div>
        <div class="meta-item">
          <el-icon><Phone /></el-icon>
          <span>联系电话: {{ taskdetail.phone }}</span>
        </div>
        <div class="meta-item">
          <el-icon><Clock /></el-icon>
          <span>发布时间: {{ formatTime(taskdetail.createTime) }}</span>
        </div>
      </div>
      
      <div class="task-content">
        <h3>任务描述</h3>
        <p>{{ taskdetail.content }}</p>
      </div>
      
      <div class="task-reward">
        <el-tag type="warning" size="large">
          <el-icon><Coin /></el-icon>
          奖励: {{ taskdetail.reward }} {{ taskdetail.rewardType }}
        </el-tag>
        <el-tag v-if="taskdetail.remainCount > 0" type="success" size="large">
          剩余名额: {{ taskdetail.remainCount }}个
        </el-tag>
      </div>
      
      <!-- 横向时间显示 -->
      <div class="task-time-horizontal">
        <div class="time-item">
          <span class="time-label">开始时间:</span>
          <span class="time-value">{{ formatTime(taskdetail.startTime) }}</span>
        </div>
        <div class="time-item">
          <span class="time-label">结束时间:</span>
          <span class="time-value">{{ formatTime(taskdetail.endTime) }}</span>
        </div>
      </div>
      
      <div v-if="taskdetail.address.length > 0" class="task-address">
        <h3>任务地点</h3>
        <el-tag v-for="(addr, index) in taskdetail.address" :key="index" class="address-tag">
          {{ addr }}
        </el-tag>
      </div>
      
      <div v-if="taskdetail.remark" class="task-remark">
        <h3>备注</h3>
        <p>{{ taskdetail.remark }}</p>
      </div>
      
      <div class="task-actions">
        <el-button 
          v-if="!isOwner && !isReceiver && taskdetail.remainCount > 0" 
          type="primary" 
          size="large" 
          @click="handleAcceptTask"
        >
          申请领取任务
        </el-button>
        <el-button v-if="isOwner" type="warning" size="large" @click="handleEditTask">
          编辑任务
        </el-button>
      </div>
    </el-card>
    
    <!-- 任务状态记录 -->
    <el-card class="task-history-card">
      <template #header>
        <div class="card-header">
          <span>任务状态记录</span>
        </div>
      </template>
      <el-timeline>
        <el-timeline-item
          v-for="(record, index) in taskdetail.historyRecords"
          :key="index"
          :timestamp="formatTime(record.time)"
          :type="getHistoryType(record.type)"
          placement="top"
        >
          <p>{{ record.user }} {{ record.action }} {{ record.reason ? `(原因: ${record.reason})` : '' }}</p>
        </el-timeline-item>
      </el-timeline>
    </el-card>
    
    <!-- 任务领取人列表 -->
    <el-card class="receiver-list-card">
      <template #header>
        <div class="card-header">
          <span>任务领取人 ({{ taskdetail.receiveList.length }})</span>
        </div>
      </template>
      
      <el-table :data="taskdetail.receiveList" style="width: 100%">
        <el-table-column prop="name" label="领取人" width="120" />
        <el-table-column prop="phone" label="联系电话" width="150" />
        <el-table-column prop="receiveTime" label="申请时间" width="180">
          <template #default="{row}">
            {{ formatTime(row.receiveTime) }}
          </template>
        </el-table-column>
        <el-table-column label="领取状态" width="120">
          <template #default="{row}">
            <el-tag :type="getReceiverStatusType(row.status)">
              {{ getReceiverStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="{row}">
            <el-button 
              v-if="isOwner && row.status === 1" 
              type="success" 
              size="small" 
              @click="handleConfirmReceive(row, true)"
            >
              确认领取
            </el-button>
            <el-button 
              v-if="isOwner && row.status === 1" 
              type="danger" 
              size="small" 
              @click="handleConfirmReceive(row, false)"
            >
              拒绝领取
            </el-button>
            <el-button 
              v-if="isOwner && [2,3].includes(row.status)" 
              type="danger" 
              size="small" 
              @click="handleCancelReceiver(row)"
            >
              取消资格
            </el-button>
            <el-button 
              v-if="isReceiver && row.status === 2" 
              type="primary" 
              size="small" 
              @click="handleStartTask(row)"
            >
              开始任务
            </el-button>
            <el-button 
              v-if="isReceiver && row.status === 2 && row.isStart" 
              type="warning" 
              size="small" 
              @click="handleCancelTask(row)"
            >
              取消任务
            </el-button>
            <el-button 
              v-if="isReceiver && row.isStart && !row.isFinish" 
              type="success" 
              size="small" 
              @click="handleFinishTask(row)"
            >
              完成任务
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 任务追踪 -->
    <el-card v-if="isOwner" class="task-track-card">
      <template #header>
        <div class="card-header">
          <span>任务追踪</span>
          <el-switch
            v-model="taskdetail.isTrack"
            active-text="开启追踪"
            inactive-text="关闭追踪"
            :disabled="!isOwner"
          />
        </div>
      </template>
      
      <div v-if="taskdetail.isTrack">
        <el-tabs v-model="activeReceiver" type="card">
          <el-tab-pane
            v-for="receiver in taskdetail.receiveList"
            :key="receiver.id"
            :label="receiver.name"
            :name="receiver.id.toString()"
          >
            <div v-if="receiver.trackList.length > 0" class="track-timeline">
              <el-timeline>
                <el-timeline-item
                  v-for="(track, index) in receiver.trackList"
                  :key="index"
                  :timestamp="formatTime(track.time)"
                  placement="top"
                >
                  <el-card>
                    <h4>位置更新</h4>
                    <p v-if="track.location">坐标: {{ track.location }}</p>
                    <p v-else>位置信息未记录</p>
                  </el-card>
                </el-timeline-item>
              </el-timeline>
            </div>
            <div v-else class="no-track-data">
              <el-empty description="暂无追踪数据" />
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div v-else class="track-disabled">
        <el-empty description="任务追踪未开启" />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Phone, Clock, Coin } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { ArrowLeft } from '@element-plus/icons-vue' // 引入图标

const router = useRouter()
// 当前用户是否是任务发布人
const isOwner = ref(true)
// 当前用户是否是任务领取人
const isReceiver = ref(false)
// 当前选中的领取人ID（用于追踪）
const activeReceiver = ref('1')


type StatusTextMap = {
  0: string;
  1: string;
  2: string;
  3: string;
  4: string;
  [key: number]: string; // 添加索引签名以允许数字索引
}
// 状态映射
const statusTextMap:StatusTextMap = {
  0: '未领取',
  1: '待确认',
  2: '进行中',
  3: '已取消',
  4: '已完成',
};
// 定义状态类型映射类型
type StatusTypeMap = {
  0: 'info';
  1: 'warning';
  2: 'primary';
  3: 'danger';
  4: 'success';
  [key: number]: string; // 添加索引签名以允许数字索引
}

// 定义状态文本映射类型
const statusTypeMap:StatusTextMap = {
  0: 'info',
  1: 'warning',
  2: 'primary',
  3: 'danger',
  4: 'success'
};
// 定义历史记录类型映射类型
type HistoryType = 'create' | 'apply' | 'confirm' | 'reject' | 'start' | 'cancel' | 'finish';
type HistoryTypeMap = {
  [key in HistoryType]: string;
}
const historyTypeMap :HistoryTypeMap= {
  'create': 'primary',
  'apply': 'info',
  'confirm': 'success',
  'reject': 'danger',
  'start': 'primary',
  'cancel': 'warning',
  'finish': 'success'
};


interface Receiver {
  id: number;
  name: string;
  phone: string;
  receiveTime: string;
  planStartTime: string; // 可选
  planEndTime: string; // 可选
  realStartTime: string; // 可选
  realEndTime: string; // 可选
  status: number;
  isStart: boolean;
  trackList: Array<{
    time: string;
    location: string;
  }>;
  isFinish: boolean;
  isReward: boolean;
  rewardTime: string; // 可选
  remark: string;
  reason?: string; // 可选
}
// 任务列表数据
const taskdetail = ref({
  id: 1,
  title: '快递代取服务',
  content: '帮忙从校园快递站取3个包裹送到宿舍区3号楼,包裹大小中等',
  status: "待领取",
  type: "代取快递",
  reward: 15,
  rewardType: "积分",
  remainCount: 2,
  startTime: "2023-06-01 08:00:00",
  endTime: "2023-06-30 20:00:00",
  createdBy: "user_123",
  phone: "13812345678",
  createTime: "2023-05-30 14:30:00",
  addressType: "出发地-目的地",
  address: ["校园快递站", "宿舍区3号楼"],
  isTrack: true,
  remark: "包裹上有我的名字和电话，取件码会私信发送",
  photos: [],
  receiveList: [
    {
      id: 1,
      name: "user_1234",
      phone: "13812345678",
      receiveTime: "2023-06-01 10:00:00",
      planStartTime: "2023-06-01 08:00:00",
      planEndTime: "2023-06-01 18:00:00",
      realStartTime: "2023-06-01 09:00:00",
      realEndTime: "2023-06-01 17:00:00",
      status: 1, // 1-待确认
      isStart: false,
      trackList: [],
      isFinish: false,
      isReward: false,
      rewardTime: "2023-06-01 12:00:00",
      remark: "可以帮忙取快递"
    },
    {
      id: 2,
      name: "user_456",
      phone: "13845678901",
      receiveTime: "2023-06-02 12:00:00",
      planStartTime: "2023-06-01 08:00:00",
      planEndTime: "2023-06-01 18:00:00",
      realStartTime: "2023-06-01 09:00:00",
      realEndTime: "2023-06-01 17:00:00",
      status: 2, // 2-进行中
      isStart: true,
      trackList: [
        {
          time: "2023-06-01 09:00:00",
          location: "116.404,39.915",
        },
        {
          time: "2023-06-01 09:10:00",
          location: "116.408,39.918",
        },
        {
          time: "2023-06-01 09:20:00",
          location: "116.412,39.920",
        }
      ],
      isFinish: false,
      isReward: false,
      rewardTime: "2023-06-01 12:00:00",
      remark: "顺路可以帮忙"
    }
  ],
  historyRecords: [
    {
      time: "2023-05-30 14:30:00",
      user: "user_123",
      type: "create",
      action: "发布了任务",
      reason: ""
    },
    {
      time: "2023-06-01 10:00:00",
      user: "user_1234",
      type: "apply",
      action: "申请领取任务",
      reason: "可以帮忙取快递"
    },
    {
      time: "2023-06-02 12:00:00",
      user: "user_456",
      type: "apply",
      action: "申请领取任务",
      reason: "顺路可以帮忙"
    },
    {
      time: "2023-06-02 12:30:00",
      user: "user_123",
      type: "confirm",
      action: "确认了领取",
      reason: ""
    }
  ]
})

// 格式化时间
const formatTime = (timeStr: string) => {
  return dayjs(timeStr).format('YYYY-MM-DD HH:mm')
}

// 获取任务状态标签类型
const getStatusType = (status: string) => {
  switch (status) {
    case '待领取': return 'warning'
    case '进行中': return 'primary'
    case '已完成': return 'success'
    default: return 'info'
  }
}

// 获取领取人状态文本
const getReceiverStatusText = (status:number) => {
  return statusTextMap[status] || '未知状态'
}

// 获取领取人状态标签类型
const getReceiverStatusType = (status:number) => {
  return statusTypeMap[status] || 'info'
}

// 获取历史记录类型
const getHistoryType = (type:HistoryType) => {
  return historyTypeMap[type] || 'info'
}

// 添加历史记录
const addHistoryRecord = (type:HistoryType, action:string, reason = '') => {
  taskdetail.value.historyRecords.push({
    time: new Date().toISOString(),
    user: 'current_user',
    type,
    action,
    reason
  })
}


// 返回上一页
const handleGoBack = () => {
  // 方案1：返回上一页历史记录
  router.go(-1)
  
  // 方案2：固定跳转到任务列表页（更可靠）
  // router.push('/task-list') 
}
// 处理领取任务
const handleAcceptTask = () => {
  ElMessageBox.prompt('请输入领取备注(可选)', '领取任务', {
    confirmButtonText: '提交申请',
    cancelButtonText: '取消'
  }).then(({ value }) => {
    // 这里应该是API调用
    const newReceiver: Receiver = {
      id: Date.now(),
      name: "current_user",
      phone: "13800000000",
      receiveTime: new Date().toISOString(),
      status: 1, // 1-等待确认
      isStart: false,
      trackList: [],
      isFinish: false,
      isReward: false,
      remark: value,
      reason: '',
      // 其他字段默认值
      rewardTime: new Date().toISOString(),
      planStartTime: new Date().toISOString(),
      planEndTime:new Date().toISOString(),
      realStartTime: new Date().toISOString(),
      realEndTime: new Date().toISOString(),
    }
    taskdetail.value.receiveList.push(newReceiver)
    addHistoryRecord('apply', '申请领取任务', value)
    ElMessage.success('领取申请已提交，等待发布人确认')
    isReceiver.value = true
  }).catch(() => {
    ElMessage.info('已取消领取')
  })
}

// 处理确认/拒绝领取
const handleConfirmReceive = (receiver:Receiver, isConfirm:boolean) => {
  const action = isConfirm ? 'confirm' : 'reject'
  const title = isConfirm ? '确认领取' : '拒绝领取'
  
  ElMessageBox.prompt(isConfirm ? '确认该用户领取任务?' : '请输入拒绝原因', title, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputType: isConfirm ? null : 'textarea',
    inputPlaceholder: isConfirm ? '' : '请输入拒绝原因...'
  }).then(({ value }) => {
    receiver.status = isConfirm ? 2 : 3 // 2-进行中, 3-已取消
    if (!isConfirm) {
      receiver.reason = value
    }
    addHistoryRecord(
      action, 
      isConfirm ? '确认了领取' : '拒绝了领取', 
      isConfirm ? '' : value
    )
    ElMessage.success(isConfirm ? '已确认领取' : '已拒绝领取')
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

// 处理开始任务
const handleStartTask = (receiver:Receiver) => {
  // 这里应该是API调用
  receiver.isStart = true
  addHistoryRecord('start', '开始了任务')
  ElMessage.success('任务已开始!')
}

// 处理完成任务
const handleFinishTask = (receiver:Receiver) => {
  ElMessageBox.prompt('请填写任务完成说明', '完成任务', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputType: 'textarea',
    inputPlaceholder: '请描述任务完成情况...'
  }).then(({ value }) => {
    // 这里应该是API调用
    receiver.isFinish = true
    receiver.status = 4 // 4-已完成
    addHistoryRecord('finish', '完成了任务', value)
    ElMessage.success('任务已完成!')
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

// 处理取消任务
const handleCancelTask = (receiver:Receiver) => {
  ElMessageBox.prompt('请输入取消原因', '取消任务', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputType: 'textarea',
    inputPlaceholder: '请输入取消原因...'
  }).then(({ value }) => {
    receiver.status = 3 // 3-已取消
    receiver.reason = value
    addHistoryRecord('cancel', '取消了任务', value)
    ElMessage.success('任务已取消')
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

// 处理取消领取人资格
const handleCancelReceiver = (receiver:Receiver) => {
  ElMessageBox.prompt('请输入取消原因', '取消资格', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputType: 'textarea',
    inputPlaceholder: '请输入取消原因...'
  }).then(({ value }) => {
    receiver.status = 3 // 3-已取消
    receiver.reason = value
    addHistoryRecord('cancel', '取消了领取人资格', value)
    ElMessage.success('已取消该用户资格')
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

// 处理编辑任务
const handleEditTask = () => {
  ElMessage.info('编辑功能待实现')
}
</script>

<style scoped>
.task-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.task-info-card {
  margin-bottom: 20px;
}

.task-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.task-type {
  margin-left: 15px;
  font-size: 16px;
  color: #666;
}

.task-title {
  margin: 0 0 20px;
  font-size: 24px;
  color: #333;
}

.task-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
  color: #666;
}

.meta-item {
  display: flex;
  align-items: center;
}

.meta-item .el-icon {
  margin-right: 5px;
}

.task-content {
  margin-bottom: 20px;
}

.task-content h3 {
  margin: 0 0 10px;
  font-size: 18px;
}

.task-content p {
  margin: 0;
  line-height: 1.6;
}

.task-reward {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 20px;
}

/* 横向时间样式 */
.task-time-horizontal {
  display: flex;
  gap: 30px;
  margin-bottom: 20px;
}

.time-item {
  display: flex;
  align-items: center;
}

.time-label {
  font-weight: bold;
  margin-right: 8px;
}

.time-value {
  color: #666;
}

.task-address {
  margin-bottom: 20px;
}

.task-address h3 {
  margin: 0 0 10px;
  font-size: 18px;
}

.address-tag {
  margin-right: 10px;
  margin-bottom: 10px;
}

.task-remark {
  margin-bottom: 20px;
}

.task-remark h3 {
  margin: 0 0 10px;
  font-size: 18px;
}

.task-remark p {
  margin: 0;
  line-height: 1.6;
  color: #666;
}

.task-actions {
  margin-top: 20px;
  text-align: center;
}

.task-history-card,
.receiver-list-card,
.task-track-card {
  margin-bottom: 20px;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}

.track-timeline {
  padding: 10px;
}

.no-track-data,
.track-disabled {
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.card-header-with-back {
  display: flex;
  align-items: center;
  gap: 15px;
}
</style>